package com.example.demo.security;

import com.example.demo.common.exception.CaptchaException;
import com.example.demo.common.lang.Const;
import com.example.demo.utils.RedisUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
public class CaptchaFilter extends OncePerRequestFilter {

    @Resource
    RedisUtil redisUtil;
    @Resource
    LoginFailureHandler loginFailureHandler;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String url = String.valueOf(request.getRequestURI());
        if(url.contains("/login") && request.getMethod().equals("POST")){
            try {
            //校验验证码
                validate(request);
            } catch (CaptchaException e) {
                //交给认证失败处理器
                loginFailureHandler.onAuthenticationFailure(request,response,e);
            }
            //不正确，跳转失败认证处理器
        }
        filterChain.doFilter(request,response);
    }
   //校验验证码的逻辑
    private void validate(HttpServletRequest request) {
        String code = request.getParameter("code");
        String key = request.getParameter("token");
        if(StringUtils.isBlank(code) || StringUtils.isBlank(key)){
            throw new CaptchaException("验证码错误");
        }
        if(!code.equals(redisUtil.hget(Const.CAPTCHA_KEY,key))){
            throw new CaptchaException("验证码错误");
        }
        //一个验证码不能重复验证，只能使用一次
        redisUtil.hdel(Const.CAPTCHA_KEY,key);
    }
}
